//
//  OBMomentPhotoView.m
//  WeChat
//
//  Created by 黄柳姣 on 2018/5/3.
//  Copyright © 2018年 obally. All rights reserved.
//

#import "OBMomentPhotoView.h"
#import "OBMomentPhotoItemViewModel.h"

@interface OBMomentPhotoView()
/// viewModel
@property (nonatomic, readwrite, strong) OBMomentPhotoItemViewModel *viewModel;
@end
@implementation OBMomentPhotoView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
        self.exclusiveTouch = YES; //避免连续点击响应
    }
    return self;
}
- (void)bindViewModel:(id)viewModel
{
    self.viewModel = viewModel;
    ///移除动画
    [self.layer removeAnimationForKey:@"contents"];
    ///请求图片
    @weakify(self);
    [self.layer setImageWithURL:[NSURL URLWithString:self.viewModel.picture.url] placeholder:OBPicturePlaceholder() options:YYWebImageOptionAvoidSetImage completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        @strongify(self);
        if (image && stage == YYWebImageStageFinished) {
            //图片下载完成
            self.contentMode = UIViewContentModeScaleAspectFill;
            self.layer.contentsRect = CGRectMake(0, 0, 1, 1);
            self.image = image;
            if (from != YYWebImageFromMemoryCacheFast) {
                CATransition *transition = [CATransition animation];
                transition.duration = 0.15;
                transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                transition.type = kCATransitionFade;
                [self.layer addAnimation:transition forKey:@"contents"];
            }
        }
    }];
}
#pragma mark - Override
- (void)setHidden:(BOOL)hidden{
    /// 取消当前图片的请求
    if (hidden) [self.layer cancelCurrentImageRequest];
    
    [super setHidden:hidden];
}
@end
